import { Button, Typography } from 'antd';
import { 
    AppstoreAddOutlined,
  FontSizeOutlined,
  PictureOutlined
} from '@ant-design/icons';
import { useState, useRef, useEffect } from 'react';

const { Text } = Typography;

const tools = [
  { id: 'rect', icon: <AppstoreAddOutlined />, label: '图形' },
  { id: 'text', icon: <FontSizeOutlined />, label: '文本' },
  { id: 'image', icon: <PictureOutlined />, label: '图片' },
];

export default function Sidebar({ onToolChange }) {
  const [activeTool, setActiveTool] = useState(null);
  const sidebarRef = useRef(null);

  // 点击外部区域取消高亮
  useEffect(() => {
    const handleClickOutside = (e) => {
      if (sidebarRef.current && !sidebarRef.current.contains(e.target)) {
        setActiveTool(null);
        if (onToolChange) onToolChange(null);
      }
    };

    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, []);

  const handleToolClick = (toolId) => {
    const newTool = activeTool === toolId ? null : toolId;
    setActiveTool(newTool);
    if (onToolChange) onToolChange(newTool);
  };

  return (
    <div 
      ref={sidebarRef}
      style={{ 
        width: 80,
        background: '#fff', 
        borderRight: '1px solid #f0f0f0',
        padding: '16px 0',
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center',
        userSelect: 'none'
      }}
    >
      {tools.map(tool => (
        <div 
          key={tool.id}
          style={{
            display: 'flex',
            flexDirection: 'column',
            alignItems: 'center',
            marginBottom: 40,
            width: '100%',
            cursor: 'pointer'
          }}
          onClick={() => handleToolClick(tool.id)}
        >
          <Button 
            type="text" 
            icon={tool.icon} 
            style={{
              width: 48,
              height: 48,
              fontSize: 18,
              marginBottom: 4,
              backgroundColor: activeTool === tool.id ? '#e6f7ff' : 'transparent',
              color: activeTool === tool.id ? '#1890ff' : 'rgba(0, 0, 0, 0.65)'
            }}
          />
          <Text 
            style={{ 
              fontSize: 13,
              color: activeTool === tool.id ? '#1890ff' : 'rgba(0, 0, 0, 0.45)'
            }}
          >
            {tool.label}
          </Text>
        </div>
      ))}
    </div>
  );
}